const mongoose = require('mongoose')
const dbUrl = "mongodb://localhost:27017/todo_development"
mongoose.connect(dbUrl)
mongoose.Promise = global.Promise
const Todo = require('../model/todo')

const express = require('express');
const app = express();
app.use(express.json()); //express.json 解析 JSON 格式的请求体数据（有兼容性，仅在 4.16.0+ 版本中可用）
app.use(express.urlencoded());

/** 查询任务列表 */
app.get("/list", (req, res, next) => {
  Todo.find().then(data1 => {
    const result = data1.map(item => {
      return {
        id: item.id,
        name: item.name,
        content: item.content,
        deadlineTime: item.deadlineTime,
        status: item.status,
      };
    })
    res.send({
      type: 0,
      data: result,
      total: result ? result.length : 0
    });
  });
});

/** 创建一个todo */
app.post('/create', (req, res, next) => {
  const { name, deadline, content } = req.body;
  Todo.create({ name, deadline, content }).then(() => {
    res.json({
      name,
      deadline,
      content
    });
  });
});

/** 修改一个todo */
app.post('/modify', async (req, res, next) => {
  const { name, deadline, content, id } = req.body;
  Todo.findOneAndUpdate({ _id: id }, { $set: {name, deadline, content} }).then(() => {
    res.json({
      name,
      deadline,
      content,
      id
    });
  });
});

/** 修改一个todo的状态 */
app.post('/update', async (req, res, next) => {
  const { status, id } = req.body;
  Todo.findByIdAndUpdate({ _id: id }, { $set: { status: status } }).then(() => {
    res.json({
      id,
      status,
    })
  });
});


app.use((err, req, res, next) => {
  if (err) {
    res.status(500).json({
      message: err.message
    });
  }
});

app.listen(3000, () => {
  console.log("服务启动成功！");
});